//
//  SoundRecordingViewController.m
//  MJAVFoundationDemo
//
//  Created by apple on 16/9/7.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "SoundRecordingViewController.h"

@interface SoundRecordingViewController ()

@end

@implementation SoundRecordingViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title=@"录音器";
    
    //判断手机系统与7.0比较不是上升的，那就表示当前手机系统低于等于7.0
    if ([[[UIDevice currentDevice]systemVersion]compare:@"7.0"]!=NSOrderedAscending)
    {
        //7.0第一次运行会提示，是否允许使用麦克风 AVAudioSession音频会话
        AVAudioSession *session=[AVAudioSession sharedInstance];
        NSError *sessionError=nil;
        /*
         AVAudioSession的类别(category)
         
         •AVAudioSessionCategoryAmbient
         
         –混音播放，例如雨声、汽车引擎等，可与其他音乐一起播放
         
         •AVAudioSessionCategorySoloAmbient
         
         –后台播放，其他音乐将被停止
         
         •AVAudioSessionCategoryPlayback
         
         –独占音乐播放
         
         •AVAudioSessionCategoryRecord
         
         –录制音频
         
         •AVAudioSessionCategoryPlayAndRecord
         
         –播放和录制音频
         
         •AVAudioSessionCategoryAudioProcessing
         
         –使用硬件解码器处理音频，该音频会话使用期间，不能播放或录音

         */
        //设置会话环境
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        if (session==nil)
        {
            //输出错误原因
            NSLog(@"创建session失败：%@",[sessionError description]);
        }else
        {
            //激活音频会话
            [session setActive:YES error:nil];
        }
    }
    //获取本地沙盒路径
    NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    //拼接音频名字，形成一个本地沙盒文件路径
    PlayName=[NSString stringWithFormat:@"%@/play.acc",docPath];
    //录音器设置,分别设置了音乐格式，音乐采样率，音乐频道数，音乐比特率，每频道上的音频比特率，采样位，音频存储模式，采样信号是整数还是浮点数
    recorderSettingsDict=[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:kAudioFormatMPEG4AAC],AVFormatIDKey,[NSNumber numberWithInt:1000.0],AVSampleRateKey,[NSNumber numberWithInt:2],AVNumberOfChannelsKey,[NSNumber numberWithInt:8],AVLinearPCMBitDepthKey,[NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
                          [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,nil];
    //设置音量图片数组
    volumImages=[NSMutableArray arrayWithObjects:@"RecordingSignal001",@"RecordingSignal002",@"RecordingSignal003",@"RecordingSignal004",@"RecordingSignal005",@"RecordingSignal006",@"RecordingSignal007",@"RecordingSignal008",nil];
    
    
}
//按下录音
- (IBAction)beginRecord:(id)sender
{
    //如果允许开启麦克风
    if ([self canRecord]) {
        NSError *error=nil;
        //创建录音器并且配置存储路径
        recorder=[[AVAudioRecorder alloc]initWithURL:[NSURL URLWithString:PlayName] settings:recorderSettingsDict error:&error];
        if (recorder)
        {
            recorder.meteringEnabled=YES;
            [recorder prepareToRecord];
            [recorder record];
            
             timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(levelTimer:) userInfo:nil repeats:YES];
        }else
        {
            
            NSLog(@"Error: %@ " , [error localizedDescription]);
        }
    }
}
//松开停止
- (IBAction)stopRecord:(id)sender
{
    //录音停止
    [recorder stop];
    recorder = nil;
    //结束定时器
    [timer invalidate];
    timer = nil;
    //图片重置
    _soundLoadingImageView.image = [UIImage imageNamed:@""];
}
//播放录音
- (IBAction)playRecord:(id)sender
{
    NSError *playerError;
    
    //播放
    player = nil;
    player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:PlayName] error:&playerError];
    
    if (player == nil)
    {
        NSLog(@"ERror creating player: %@", [playerError description]);
    }else{
        [player play];
    }
 
}



//定时器执行的方法
-(void)levelTimer:(NSTimer*)timer
{
    //call to refresh meter values刷新平均和峰值功率,此计数是以对数刻度计量的,-160表示完全安静，0表示最大输入值
    [recorder updateMeters];
    const double ALPHA = 0.05;
    double peakPowerForChannel = pow(10, (0.05 * [recorder peakPowerForChannel:0]));
    lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * lowPassResults;
    
    NSLog(@"Average input: %f Peak input: %f Low pass results: %f", [recorder averagePowerForChannel:0], [recorder peakPowerForChannel:0], lowPassResults);
    
    //根据音量大小切换音量显示图片
    if (lowPassResults>=0.8) {
        _soundLoadingImageView.image = [UIImage imageNamed:[volumImages objectAtIndex:7]];
    }else if(lowPassResults>=0.7){
        _soundLoadingImageView.image = [UIImage imageNamed:[volumImages objectAtIndex:6]];
    }else if(lowPassResults>=0.6){
        _soundLoadingImageView.image = [UIImage imageNamed:[volumImages objectAtIndex:5]];
    }else if(lowPassResults>=0.5){
        _soundLoadingImageView.image = [UIImage imageNamed:[volumImages objectAtIndex:4]];
    }else if(lowPassResults>=0.4){
        _soundLoadingImageView.image = [UIImage imageNamed:[volumImages objectAtIndex:3]];
    }else if(lowPassResults>=0.3){
        _soundLoadingImageView.image = [UIImage imageNamed:[volumImages objectAtIndex:2]];
    }else if(lowPassResults>=0.2){
        _soundLoadingImageView.image = [UIImage imageNamed:[volumImages objectAtIndex:1]];
    }else if(lowPassResults>=0.1){
        _soundLoadingImageView.image = [UIImage imageNamed:[volumImages objectAtIndex:0]];
    }else{
        _soundLoadingImageView.image = [UIImage imageNamed:[volumImages objectAtIndex:0]];
    }
}

//判断是否可以录音
-(BOOL)canRecord
{
    __block BOOL isCanRecord=YES;
    if ([[[UIDevice currentDevice]systemVersion]compare:@"7.0"]!=NSOrderedAscending)
    {
         AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        //响应授权的方法
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted)
             {
                 //grant  是否授权
                 if(granted)
                 {
                     isCanRecord=YES;
                 }else
                 {
                     isCanRecord=NO;
                     dispatch_async(dispatch_get_main_queue(), ^{
                         [MBProgressHUD showError:@"app需要访问您的麦克风。\n请启用麦克风-设置/隐私/麦克风"];
                        
                     });
                 }
             }];

        }
    }
    return isCanRecord;
    
}
@end
